package com.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.order.api.StockFeignService;
import com.example.order.common.R;
import com.example.order.mapper.OrderMapper;
import com.example.order.pojo.Order;
import com.example.order.pojo.Stock;
import com.example.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;


/**
 * @Description TODO
 * @Author JFeng
 * @Date 2024/5/20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StockFeignService stockFeignService;


    @Override
//    @Transactional
    @GlobalTransactional // 分布式事务seata
    public R<Order> addOrder(BigDecimal totalAmount) {
        R<Order> r = new R<>();
        Order order = new Order();
        order.setTotalAmount(totalAmount);
        int num = orderMapper.insert(order);
        R<Stock> reduce = stockFeignService.reduce(1);
        String msg = "";
        if (reduce.isStatus()) {
            msg = "操作成功";
        } else {
            msg = reduce.getMessage();
        }
        int a = 0 / 0;
        r = num == 1 ? r.success(order, msg) : r.error(order, msg);
        return r;
    }


    /**
     * insert会回滚，订单不会插入；因为是本地事务，远程库存服务会扣减库存
     * @param totalAmount
     * @return
     */
//    @Override
//    @Transactional
//    public R<Order> addOrder(BigDecimal totalAmount) {
//        R<Order> r = new R<>();
//        Order order = new Order();
//        order.setTotalAmount(totalAmount);
//        int num = orderMapper.insert(order);
//        R<Stock> reduce = stockFeignService.reduce(1);
//        int a = 0/ 0;
//        r = num == 1 ? r.success(order, "操作成功") : r.error(order, "操作失败");
//        return r;
//    }
}
